package lib.core.commands
{
	import flash.utils.getQualifiedClassName;
	
	import lib.config.ModuleConfig;
	import lib.core.com.modules.BaseModule;
	import lib.core.controller.RequestUrlInfo;
	import lib.core.view.BaseModuleMediator;
	
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.command.SimpleCommand;

	public class ModuleStartupCommand extends SimpleCommand
	{		
		override public function execute(notification:INotification):void
		{
			// We retrieve the module that was loaded to the application from the notification's body
			var module:BaseModule = notification.getBody() as BaseModule;
			// now we retrieve the module name from the module's class name 
			var moduleName:String = flash.utils.getQualifiedClassName(module);
			moduleName = moduleName.substr(moduleName.lastIndexOf(":")+1);
			
			var mediator:Class = Class(ModuleConfig.getModuleMediator(moduleName));
			
			// Check if there is already a mediator for this module
			var mediatorName:String = mediator.NAME;
			//mediatorName = mediatorName.substr(mediatorName.lastIndexOf(":")+1);
			
			var mediatorInstance:BaseModuleMediator = facade.retrieveMediator(mediatorName) as BaseModuleMediator;
			
			if (!mediatorInstance)
			{		
				mediatorInstance = new mediator(module) as BaseModuleMediator;
			
				// finally we register the appropriate mediator and pass the loaded module as a parameter
				facade.registerMediator(mediatorInstance);
			}
			var url:RequestUrlInfo = new RequestUrlInfo(notification.getType());
			
			mediatorInstance.initModule(url);
			mediatorInstance.preExecute();
			if (!mediatorInstance.hasOwnProperty("execute"+url.action))
			{		
				url.setActionDefault();
			}	
			mediatorInstance["execute"+url.action]();	
		}
	}
}